package com.risetechnology.utils.threads;

import java.io.File;
import java.util.ArrayList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.text.Html;

import com.risetechnology.common.Shared;
import com.risetechnology.data.ShopIngredient;
import com.risetechnology.data.Shopping;

public class SendEmailShopingItem extends AsyncTask<Void, Void, String> {
	private ProgressDialog mDialog;
	private Activity mContext;
	private Shopping mShopping;
	private String email;

	public SendEmailShopingItem(Context context, Shopping shopping, String email) {
		mShopping = shopping;
		this.email = email;
		Activity activity = (Activity) context;
		while (activity.getParent() != null) {
			activity = activity.getParent();
		}
		mContext = activity;
		mDialog = new ProgressDialog(activity);
		mDialog.setMessage("Loading...");
		mDialog.setCancelable(false);
	}

	@Override
	protected String doInBackground(Void... params) {
		ArrayList<ShopIngredient> ingredientList = new ArrayList<ShopIngredient>();
		Shared.dbAdapter.getIngredients(mShopping.getId(), ingredientList);
		StringBuilder sendEmailContent = new StringBuilder();
		for (ShopIngredient item : ingredientList) {
			sendEmailContent.append(item.toString() + "\n");
		}
		return sendEmailContent.toString();
	}

	@Override
	protected void onPostExecute(String result) {
		if (mDialog.isShowing()) {
			mDialog.dismiss();
		}
		if (result != null) {
			try {
				Intent emailIntent = new Intent(Intent.ACTION_SENDTO,
						Uri.fromParts("mailto", email, null));
				emailIntent.putExtra(Intent.EXTRA_SUBJECT, mShopping.getName());
				emailIntent.putExtra(Intent.EXTRA_TEXT, result);
				mContext.startActivity(emailIntent);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		super.onPostExecute(result);
	}

	@Override
	protected void onPreExecute() {
		mDialog.show();
		super.onPreExecute();
	}

}
